import 'dart:async';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class RegisterViewModel extends GetxController {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController codeController = TextEditingController();
  final TextEditingController pwdController = TextEditingController();
  final TextEditingController pwd1Controller = TextEditingController();
  final second = 60.obs;
  Timer? _timer;

  void register() {
    String phone = phoneController.text;
    String code = codeController.text;
    String pwd = pwdController.text;
    String pwd1 = pwd1Controller.text;

    if (phone.isEmpty) {
      Fluttertoast.showToast(msg: "手机号不能为空");
      return;
    }

    if (!phone.isPhoneNumber) {
      Fluttertoast.showToast(msg: "请输入正确的手机号");
      return;
    }

    if (code.isEmpty) {
      Fluttertoast.showToast(msg: "验证码不能为空");
      return;
    }

    if (pwd.isEmpty) {
      Fluttertoast.showToast(msg: "密码不能为空");
      return;
    }

    if (pwd != pwd1) {
      Fluttertoast.showToast(msg: "两次密码不一致");
      return;
    }

    Fluttertoast.showToast(msg: "注册成功");
    Get.back();
  }

  void sendCode() {
    String phone = phoneController.text;
    if (phone.isEmpty) {
      Fluttertoast.showToast(msg: "手机号不能为空");
      return;
    }

    if (!phone.isPhoneNumber) {
      Fluttertoast.showToast(msg: "请输入正确的手机号");
      return;
    }

    if (second.value != 60) {
      return;
    }

    Fluttertoast.showToast(msg: "验证码发送成功");

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      second.value -= 1;
      if (second.value == 0) {
        timer.cancel();
        second.value = 60;
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null && _timer!.isActive) {
      _timer!.cancel();
    }
  }
}
